package stack.era.domain;

import java.util.ArrayList;
import java.util.HashMap;

import stack.era.database.DatabaseHome;
import stack.era.domain.character.Character;
import stack.era.domain.character.PlayerCharacter;
import stack.era.domain.location.Location;
import stack.era.domain.town.Town;
import stack.era.domain.world.World;

public class DomainController {

	private static DomainController instance = null;

	private HashMap<String, DomainObject> domainSummary;
	private boolean gameLoaded;

	private DomainController() {
		domainSummary = new HashMap<String, DomainObject>();
		this.gameLoaded = false;
	}

	public synchronized static DomainController getInstance() {
		if (instance == null) {
			instance = new DomainController();
		}
		return instance;
	}

	public void registerToSummary(String name, DomainObject o) {
		domainSummary.put(name, o);
	}

	public void startNewGame(String playerName) {
		DomainHome domain = DomainHome.getInstance();
		domain.registerCharacter(playerName, new PlayerCharacter(playerName));
		domain.getWorld().setPlayerCharacterName(playerName);
	}

	public void saveGame() {
		DomainHome domain = DomainHome.getInstance();
		DatabaseHome data = DatabaseHome.getInstance();
		data.saveCharacters(domain.getAllCharacters());
		data.saveTowns(domain.getAllTowns());
		data.saveLocations(domain.getAllLocations());
		data.saveWorld(domain.getWorld());
	}

	public void loadGame() {
		DatabaseHome data = DatabaseHome.getInstance();
		ArrayList<Character> characters = data.loadCharacters();
		ArrayList<Town> towns = data.loadTowns();
		ArrayList<Location> locations = data.loadLocations();
		World world = data.loadWorld();
		if (characters != null && towns != null && locations != null
				&& world != null) {
			this.gameLoaded = true;
			DomainHome domain = DomainHome.getInstance();
			for (Character c : characters) {
				domain.registerCharacter(c.getName(), c);
			}
			for (Town t : towns) {
				domain.registerTown(t.getName(), t);
			}
			for (Location l : locations) {
				domain.registerLocation(l.getName(), l);
			}
			domain.setWorld(world);
		} else {
			this.gameLoaded = false;
		}
	}

	public void updateDomain() {
		ArrayList<DomainObject> summary = this.getDomainSummary();
		for (DomainObject o : summary) {
			o.update();
		}
	}

	public ArrayList<DomainObject> getDomainSummary() {
		return new ArrayList<DomainObject>(domainSummary.values());
	}

	public boolean loadedGameFound() {
		return gameLoaded;
	}

}
